<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Java Swing Events</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Java, Swing, events, tutorial, programming, Linux">
<meta name="description" content="This part of the Java Swing tutorial covers events.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Java Swing Events</h1>


<p>
Events are an important part in any GUI program.
All GUI applications are event-driven. An application reacts to different 
event types which are generated during its life. Events are generated mainly 
by the user of an application. But they can be generated by other means as well. 
e.g. internet connection, window manager, timer.
In the event model, there are three participants:
</p>

<ul>
<li>event source</li>
<li>event object</li>
<li>event listener</li>
</ul>

<p>
The <b>Event source</b> is the object whose state changes. It generates Events. 
The <b>Event object</b> (Event) encapsulates the state changes in the event source.
The <b>Event listener</b> is the object that wants to be notified. Event source object 
delegates the task of handling an event to the event listener. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
Event handling in Java Swing toolkit is very powerful and flexible. 
Java uses Event Delegation Model.
We specify the objects that are to be notified when a specific event occurs.
</p>


<h2>An event object</h2>


<p>
When something happens in the application, an event object is created. 
For example, when we click on the button or select
an item from a list. There are several types of events. 
An <code>ActionEvent</code>, <code>TextEvent</code>, 
<code>FocusEvent</code>, <code>ComponentEvent</code> etc. 
Each of them is created under specific conditions. 
</p>

<p>
Event object has information about an event, that has happened. In the next 
example, we will analyze an <code>ActionEvent</code> in more detail. 
</p>


<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Example extends JFrame implements ActionListener {

    private JList list;
    private DefaultListModel model;

    public Example() {
        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(null);

        model = new DefaultListModel();
        list = new JList(model);
        list.setBounds(150, 30, 220, 150);

        JButton okButton = new JButton("Ok");
        okButton.setBounds(30, 35, 80, 25);

        okButton.addActionListener(this);

        panel.add(okButton);
        panel.add(list);
        add(panel);

        setTitle("Event object");
        setSize(420, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {

        Locale locale = Locale.getDefault();
        Date date = new Date(e.getWhen());
        String s = DateFormat.getTimeInstance(DateFormat.SHORT,
                locale).format(date);

        if (!model.isEmpty()) {
            model.clear();
        }

        if (e.getID() == ActionEvent.ACTION_PERFORMED) {
            model.addElement(" Event Id: ACTION_PERFORMED");
        }

        model.addElement(" Time: " + s);

        String source = e.getSource().getClass().getName();
        model.addElement(" Source: " + source);

        int mod = e.getModifiers();

        StringBuffer buffer = new StringBuffer(" Modifiers: ");

        if ((mod &amp; ActionEvent.ALT_MASK) > 0) {
            buffer.append("Alt ");
        }

        if ((mod &amp; ActionEvent.SHIFT_MASK) > 0) {
            buffer.append("Shift ");
        }

        if ((mod &amp; ActionEvent.META_MASK) > 0) {
            buffer.append("Meta ");
        }

        if ((mod &amp; ActionEvent.CTRL_MASK) > 0) {
            buffer.append("Ctrl ");
        }

        model.addElement(buffer);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The code example shows a button and a list. If we click on the button, 
information about the event is displayed in the list.
In our case, we are talking about an <code>ActionEvent</code> class. 
The data will be the time, when the event occurred, the id of the event, 
the event source and the modifier keys. 
</p>

<pre class="explanation">
public void actionPerformed(ActionEvent event) {
</pre>

<p>
The <code>ActionEvent</code> is an instance of the event, that has occurred.
</p>


<pre class="explanation">
Locale locale = Locale.getDefault();
Date date = new Date(e.getWhen());
String s = DateFormat.getTimeInstance(DateFormat.SHORT,
        locale).format(date);
</pre>

<p>
Here we get the time, when the event occurred. The <code>getWhen()</code> method 
returns time value in milliseconds. So we must format it appropriately.
</p>


<pre class="explanation">
String source = event.getSource().getClass().getName();
model.addElement(" Source: " + source);
</pre>

<p>
Here we add the name of the source of the event to the list. 
In our case the source is a <code>JButton</code>.
</p>

<pre class="explanation">
int mod = event.getModifiers();
</pre>

<p>
We get the modifier keys. It is a bitwise-or of the modifier constants.
</p>

<pre class="explanation">
if ((mod &amp; ActionEvent.SHIFT_MASK) > 0)
    buffer.append("Shift ");
</pre>

<p>
Here we determine, whether we have pressed a Shift key. 
</p>


<img src="/img/gui/javaswing/eventobject.png" alt="Event Object">
<div class="figure">Figure: Event Object</div>


<h2>Implementation</h2>

<p>
There are several ways, how we can implement event handling in Java Swing toolkit. 
</p>

<ul>
<li>Anonymous inner class</li>
<li>Inner class</li>
<li>Derived class</li>
</ul>


<h2>Anonymous inner class</h2>


<p>
We will illustrate these concepts on a simple event example. 
</p>


<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class AnonymousInnerClassExample extends JFrame {


    public AnonymousInnerClassExample() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(null);

        JButton closeButton = new JButton("Close");
        closeButton.setBounds(40, 50, 80, 25);

        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });

        panel.add(closeButton);
        add(panel);

        setTitle("Anonymous inner class");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                AnonymousInnerClassExample ex =
                        new AnonymousInnerClassExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In this example, we have a button that closes the window upon clicking. 
</p>

<pre class="explanation">
JButton closeButton = new JButton("Close");
</pre>

<p>
The button is the <b>event source</b>. It will generate events.
</p>

<pre class="explanation">
closeButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        System.exit(0);
    }
});
</pre>

<p>
Here we <b>register</b> an action listener with the button. This way, 
the events are sent to the <b>event target</b>.
The event target in our case is <code>ActionListener</code> class. 
In this code, we use an <b>anonymous inner class</b>.
</p>


<h2>Inner class</h2>

<p>
Here we implement the example using an inner <code>ActionListener</code> class. 
</p>

<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class InnerClassExample extends JFrame {

    public InnerClassExample() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(null);

        JButton closeButton = new JButton("Close");
        closeButton.setBounds(40, 50, 80, 25);

        ButtonCloseListener listener = new ButtonCloseListener();
        closeButton.addActionListener(listener);

        panel.add(closeButton);
        add(panel);

        setTitle("Inner class example");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class ButtonCloseListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                InnerClassExample ex = new InnerClassExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
We have on close button on the panel. The listener is defined inside
an inner class, which has a name.
</p>

<pre class="explanation">
ButtonCloseListener listener = new ButtonCloseListener();
closeButton.addActionListener(listener);
</pre>

<p>
Here we have a non anonymous inner class. 
</p>

<pre class="explanation">
class ButtonCloseListener implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
}
</pre>

<p>
The button listener is defined here. 
</p>


<h2>A derived class implementing the listener</h2>

<p>
The following example will derive a class from a component and implement an 
action listener inside the class.
</p>

<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class DerivedClassExample extends JFrame {

    public DerivedClassExample() {

        initUI();
    }

    public final void initUI() {
        
        JPanel panel = new JPanel();
        panel.setLayout(null);

        MyButton closeButton = new MyButton("Close");
        closeButton.setBounds(40, 50, 80, 25);

        panel.add(closeButton);
        add(panel);

        setTitle("Derived class");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class MyButton extends JButton implements ActionListener {

        public MyButton(String text) {
            super.setText(text);
            addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                DerivedClassExample ex = new DerivedClassExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In this example, we create a MyButton class, which will implement the action listener. 
</p>

<pre class="explanation">
MyButton closeButton = new MyButton("Close");
</pre>

<p>
Here we create the MyButton custom class.
</p>

<pre class="explanation">
class MyButton extends JButton implements ActionListener {
</pre>

<p>
The MyButton class is extended from the <code>JButton</code> class. It implements the
<code>ActionListener</code> interface. This way, the event handling 
is managed within the MyButton class. 
</p>

<pre class="explanation">
addActionListener(this);
</pre>

<p>
Here we add the action listener to the MyButton class. 
</p>


<h2>Multiple sources</h2>


<p>
A listener can be plugged into several sources. This will be 
explained in the next example.
</p>


<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;

public class MultipleSources extends JFrame {

    JLabel statusbar;

    public MultipleSources() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        statusbar = new JLabel(" ZetCode");

        statusbar.setBorder(BorderFactory.createEtchedBorder(
                EtchedBorder.RAISED));

        panel.setLayout(null);

        JButton close = new JButton("Close");
        close.setBounds(40, 30, 80, 25);
        close.addActionListener(new ButtonListener());

        JButton open = new JButton("Open");
        open.setBounds(40, 80, 80, 25);
        open.addActionListener(new ButtonListener());

        JButton find = new JButton("Find");
        find.setBounds(40, 130, 80, 25);
        find.addActionListener(new ButtonListener());

        JButton save = new JButton("Save");
        save.setBounds(40, 180, 80, 25);
        save.addActionListener(new ButtonListener());

        panel.add(close);
        panel.add(open);
        panel.add(find);
        panel.add(save);

        add(panel);
        add(statusbar, BorderLayout.SOUTH);

        setTitle("Multiple Sources");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JButton o = (JButton) e.getSource();
            String label = o.getText();
            statusbar.setText(" " + label + " button clicked");
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MultipleSources ms = new MultipleSources();
                ms.setVisible(true);
            }
        });
    }
}
</pre>


<p>
We create four buttons and a statusbar. The statusbar will display an 
informative message upon clicking on the
button.
</p>


<pre class="explanation">
close.addActionListener(new ButtonListener());
...
open.addActionListener(new ButtonListener());
...
</pre>

<p>
Each button will be registered against a <code>ButtonListener</code> class.
</p>


<pre class="explanation">
JButton o = (JButton) e.getSource();
String label = o.getText();
</pre>

<p>
Here we determine, which button was pressed.
</p>

<pre class="explanation">
statusbar.setText(" " + label + " button clicked")
</pre>

<p>
We update the statusbar.
</p>


<img src="/img/gui/javaswing/multiplesources.png" alt="Multiple Sources">
<div class="figure">Figure: Multiple Sources</div>


<h2>Multiple listeners</h2>

<p>
We can register several listeners for one event. 
</p>


<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.Calendar;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;


public class MultipleListeners extends JFrame {

    private JLabel statusbar;
    private JSpinner spinner;
    private static int count = 0;

    public MultipleListeners() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        statusbar = new JLabel("0");

        statusbar.setBorder(BorderFactory.createEtchedBorder(
                EtchedBorder.RAISED));

        panel.setLayout(null);

        JButton add = new JButton("+");
        add.setBounds(40, 30, 80, 25);
        add.addActionListener(new ButtonListener1());
        add.addActionListener(new ButtonListener2());

        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);

        SpinnerModel yearModel = new SpinnerNumberModel(currentYear,
                currentYear - 100,
                currentYear + 100,
                1);

        spinner = new JSpinner(yearModel);
        spinner.setEditor(new JSpinner.NumberEditor(spinner, "#"));

        spinner.setBounds(190, 30, 80, 25);

        panel.add(add);
        panel.add(spinner);

        add(panel);
        add(statusbar, BorderLayout.SOUTH);

        setTitle("Multiple Listeners");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class ButtonListener1 implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            Integer val = (Integer) spinner.getValue();
            spinner.setValue(++val);
        }
    }

    class ButtonListener2 implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            statusbar.setText(Integer.toString(++count));
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MultipleListeners ml = new MultipleListeners();
                ml.setVisible(true);
            }
        });
    }
}
</pre>


<p>
In this example, we have a button, spinner and a statusbar.  We use two button 
listeners for one event. One click of a button will add one year to the spinner 
component and update the statusbar. The statusbar will show, how many times 
we have clicked on the button. 
</p>

<pre class="explanation">
add.addActionListener(new ButtonListener1());
add.addActionListener(new ButtonListener2());
</pre>

<p>
We register two button listeners. 
</p>

<pre class="explanation">
 SpinnerModel yearModel = new SpinnerNumberModel(currentYear,
                              currentYear - 100,
                              currentYear + 100,
                              1);
 spinner = new JSpinner(yearModel);
</pre>

<p>
Here we create the spinner component. We use a year model for the spinner. 
The <code>SpinnerNumberModel</code>
arguments are initial value, min, max values and the step. 
</p>

<pre class="explanation">
 spinner.setEditor(new JSpinner.NumberEditor(spinner, "#"));
</pre>

<p>
We remove the thousands separator.
</p>


<pre class="explanation">
Integer val = (Integer) spinner.getValue();
spinner.setValue(++val);
</pre>

<p>
Here we increase the year number. 
</p>


<img src="/img/gui/javaswing/multiplelisteners.png" alt="Multiple Listeners">
<div class="figure">Figure: Multiple Listeners</div>


<h2>Removing listeners</h2>

<p>
The Java Swing toolkit enables us to remove the registered listeners. 
</p>

<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class RemoveListenerExample extends JFrame {

    private JLabel text;
    private JButton add;
    private JCheckBox active;
    private ButtonListener buttonlistener;
    private static int count = 0;

    public RemoveListenerExample() {


        JPanel panel = new JPanel();

        panel.setLayout(null);

        add = new JButton("+");
        add.setBounds(40, 30, 80, 25);
        buttonlistener = new ButtonListener();

        active = new JCheckBox("Active listener");
        active.setBounds(160, 30, 140, 25);

        active.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent event) {
                if (active.isSelected()) {
                    add.addActionListener(buttonlistener);
                } else {
                    add.removeActionListener(buttonlistener);
                }
            }
        });

        text = new JLabel("0");
        text.setBounds(40, 80, 80, 25);

        panel.add(add);
        panel.add(active);
        panel.add(text);

        add(panel);

        setTitle("Remove listener");
        setSize(310, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            text.setText(Integer.toString(++count));
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                RemoveListenerExample ex = new RemoveListenerExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
We have three components on the panel. A button, check box and a label. By toggling 
the check box, we add or remove the listener for a button.
</p>

<pre class="explanation">
buttonlistener = new ButtonListener();
</pre>

<p>
We have to create a non anonymous listener, if we want to later remove it.
We need a reference to it. 
</p>

<pre class="explanation">
if (active.isSelected()) {
    add.addActionListener(buttonlistener);}
else {
    add.removeActionListener(buttonlistener);
}
</pre>

<p>
We determine, whether the check box is selected. Then we add or remove the listener. 
</p>


<img src="/img/gui/javaswing/removelistener.png" alt="Remove listener">
<div class="figure">Figure: Remove listener</div>



<h2>Moving a window</h2>

<p>
The following example will look for a position of a window on the screen. 
</p>

<pre class="code">
package zetcode;

import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class MovingWindowExample extends JFrame
        implements ComponentListener {

    private JLabel labelx;
    private JLabel labely;

    public MovingWindowExample() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(null);

        labelx = new JLabel("x: ");
        labelx.setFont(new Font("Serif", Font.BOLD, 14));
        labelx.setBounds(20, 20, 60, 25);

        labely = new JLabel("y: ");
        labely.setFont(new Font("Serif", Font.BOLD, 14));
        labely.setBounds(20, 45, 60, 25);

        panel.add(labelx);
        panel.add(labely);

        add(panel);

        addComponentListener(this);

        setTitle("Moving window");
        setSize(310, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void componentResized(ComponentEvent e) {
    }

    public void componentMoved(ComponentEvent e) {
        int x = e.getComponent().getX();
        int y = e.getComponent().getY();
        labelx.setText("x: " + x);
        labely.setText("y: " + y);
    }

    public void componentShown(ComponentEvent e) {
    }

    public void componentHidden(ComponentEvent e) {
    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MovingWindowExample ex = new MovingWindowExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
The example shows the current window coordinates on the panel. 
To get the window position, we use the <code>ComponentListener</code>.
</p>

<pre class="explanation">
labelx.setFont(new Font("Serif", Font.BOLD, 14));
</pre>

<p>
We make the font bigger, the default one is a bit small.
</p>

<pre class="explanation">
int x = e.getComponent().getX();
int y = e.getComponent().getY();
</pre>

<p>
Here we get the x and the y positions.
</p>

<p>
Notice, that we have to implement all four methods, that are available in the 
<code>ComponentListener</code>. Even, if we do not use them. 
</p>


<img src="/img/gui/javaswing/movingwindow.png" alt="Moving a window">
<div class="figure">Figure: Moving a window</div>



<h2>Adapters</h2>

<p>
Adapters are convenient classes. In the previous code example, we had to implement all 
four methods of a <code>ComponentListener</code> class. Even if we did not use them.    
To avoid unnecessary coding, we can use adapters. Adapter is a class that implements all 
necessary methods. They are empty. We then use only those methods, that we actually need. 
There is no adapter for a button click event.  Because there we have only one method to implement. 
The <code>actionPerformed()</code> method.
We can use adapters in situations, where we have more than one method to implement. 
</p>
 
<p>
The following example is a rewrite of the previous one, using a <code>ComponentAdapter</code>.
</p>

<pre class="code">
package zetcode;

import java.awt.Font;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class AdapterExample extends JFrame {

    private JLabel labelx;
    private JLabel labely;

    public AdapterExample() {

        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        panel.setLayout(null);

        labelx = new JLabel("x: ");
        labelx.setFont(new Font("Serif", Font.BOLD, 14));
        labelx.setBounds(20, 20, 60, 25);

        labely = new JLabel("y: ");
        labely.setFont(new Font("Serif", Font.BOLD, 14));
        labely.setBounds(20, 45, 60, 25);


        panel.add(labelx);
        panel.add(labely);

        add(panel);
        addComponentListener(new MoveAdapter());

        setTitle("Adapter example");
        setSize(310, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);        
    }

    class MoveAdapter extends ComponentAdapter {

        @Override
        public void componentMoved(ComponentEvent e) {
            int x = e.getComponent().getX();
            int y = e.getComponent().getY();
            labelx.setText("x: " + x);
            labely.setText("y: " + y);
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                AdapterExample ex = new AdapterExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
This example is a rewrite of the previous one. Here we use the <code>ComponentAdapter</code>.
</p>

<pre class="explanation">
addComponentListener(new MoveAdapter());
</pre>

<p>
Here we register the component listener. 
</p>

<pre class="explanation">
class MoveAdapter extends ComponentAdapter {

    @Override
    public void componentMoved(ComponentEvent e) {
        int x = e.getComponent().getX();
        int y = e.getComponent().getY();
        labelx.setText("x: " + x);
        labely.setText("y: " + y);
    }
}
</pre>

<p>
Inside the MoveAdapter inner class, we define the <code>componentMoved()</code> 
method. All the other methods are left empty.
</p>


<p>
This part of the Java Swing tutorial was dedicated to Swing events. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 25, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>